package com.example.fastdfs_demo.service.impl;

import com.example.fastdfs_demo.service.UploadFileService;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.fdfs.ThumbImageConfig;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;


@Service
public class UploadFileServiceImpl implements UploadFileService {

  private final static Logger log = LoggerFactory.getLogger(UploadFileServiceImpl.class);

  @Autowired
  private FastFileStorageClient storageClient;

  @Autowired
  private ThumbImageConfig thumbImageConfig;



  @Override
  public String UploadFilesToServer(MultipartFile[] files) throws Exception {
    String result = new String();

    try {
      for (int i = 0; i < files.length; i++) {
        log.info("开始上传文件==============>{}", files[i].getOriginalFilename());
        // 上传

        StorePath storePath = null;
        BufferedImage image = ImageIO.read(files[i].getInputStream());
        if (image == null) {// 判断是否为图片
          storePath = this.storageClient.uploadFile(files[i].getInputStream(), files[i].getSize(), FilenameUtils.getExtension(files[i].getOriginalFilename()), null);

        } else {
          storePath = storageClient.uploadImageAndCrtThumbImage(files[i].getInputStream(), files[i].getSize(), FilenameUtils.getExtension(files[i].getOriginalFilename()), null);
          log.info("缩略图路径=========>{}", thumbImageConfig.getThumbImagePath(storePath.getPath()));
        }

        log.info("文件存储在服务器的路径==============>{}", storePath.getFullPath());

        result = storePath.getFullPath();

        if (image != null) {
          log.info("缩略图路径=========>{}", thumbImageConfig.getThumbImagePath(storePath.getPath()));
        }
        log.info("文件上传服务器成功=========>{}", files[i].getOriginalFilename());
      }


    } catch (Exception e) {
      log.info("文件上传失败 ==> ,{}" + e.getMessage());
      // fileList.clear();
      log.info("文件上传失败，正在清理文件==================>,{}", e.getMessage());
      e.printStackTrace();
      throw new Exception(e.getMessage());
    } finally {
      return result;
    }
  }

}
